package com.log6z.dashborad.exception;



import com.log6z.dashborad.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author
 * @date 2018/8/30 全局异常处理器
 */
@Order(-1)
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 全局异常
     *
     * @param e the e
     * @return R
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public AjaxResult handleGlobalException(HttpServletRequest httpRequest, Exception e) {
        String requestUrl = getRequestUrl(httpRequest);
        log.error("全局异常信息,url={},错误信息={}",requestUrl, e.getMessage(), e);
        return AjaxResult.error("内部错误,请联系管理员");
    }

    /**
     * PlatformException.
     *
     * @param e the e
     * @return R
     */
    @ExceptionHandler(PlatformException.class)
    @ResponseStatus(HttpStatus.OK)
    public AjaxResult handlePlatformException(HttpServletRequest httpRequest, PlatformException e) {
        String requestUrl = getRequestUrl(httpRequest);
        log.error("系统平台异常信息 url={},错误信息={}",requestUrl, e.getMessage());
        return AjaxResult.error(e.getCode(), e.getMessage());
    }

    /**
     * 处理数据校验异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    public AjaxResult handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        Map<String, String> messageMap = new HashMap<>();
        fieldErrors.forEach(fieldError -> {
            messageMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        log.error("数据校验发生异常: ", e);
        StringBuilder errorMessage = new StringBuilder("数据校验发生异常");
        errorMessage.append(messageMap.toString());
        return AjaxResult.error(errorMessage.toString());
    }


    /**
     * 捕获系统中400异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler({
            HttpRequestMethodNotSupportedException.class,
            HttpMessageNotReadableException.class,
            MethodArgumentTypeMismatchException.class,
            MissingServletRequestParameterException.class,
            //MethodArgumentNotValidException.class,
    })
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public AjaxResult handleBodyValidException(HttpServletRequest httpRequest, Exception exception) {
        String requestUrl = getRequestUrl(httpRequest);
        log.error("请求数据格式错误，url={}",requestUrl,exception);
        return AjaxResult.error("请求数据格式错误," + exception.getMessage());
    }

    /**
     * 获取请求地址
     *
     * @param httpRequest
     */
    private String getRequestUrl(HttpServletRequest httpRequest) {
        return httpRequest.getServletPath();
    }
}
